//
// Created by 33145 on 2023/6/1.
//

#include "io_thread.h"
#include "../common/util.h"
#include "../common/log.h"

#include <cassert>

namespace rocket {

  IOThread::IOThread() {
    int rt = sem_init(&_init_semaphore, 0, 0);
    assert(rt == 0);
    rt = sem_init(&_start_semaphore, 0, 0);
    assert(rt == 0);
    pthread_create(&_thread, nullptr, &mainFunc, this);

    sem_wait(&_init_semaphore);
    LOG_DEBUG("IOThread [%d] create success", _thread_id);
  }

  IOThread::~IOThread() {
    _eventloop->stop();
    sem_destroy(&_init_semaphore);  // TODO 感觉这里的同步好像不是很严谨
    sem_destroy(&_start_semaphore);

    pthread_join(_thread, nullptr);

  }

  EventLoop::ptr IOThread::getEventLoop() {
    return _eventloop;
  }

  void IOThread::start() {
    LOG_DEBUG("Now invoke IOThread %d", _thread_id);
    sem_post(&_start_semaphore);
  }

  void IOThread::join() {
    pthread_join(_thread, nullptr);
  }

  void *IOThread::mainFunc(void *arg) {
    auto thread = static_cast<IOThread*>(arg);
    thread->_eventloop = std::make_shared<EventLoop>();
    thread->_thread_id = getThreadId();
    sem_post(&thread->_init_semaphore);

    sem_wait(&thread->_start_semaphore);  // 等待被start唤醒

    LOG_DEBUG("IOThread %d start loop ", thread->_thread_id);
    thread->_eventloop->loop();
    LOG_DEBUG("IOThread %d end loop ", thread->_thread_id);
    return nullptr;
  }

}